<?php

class IndexController extends Zend_Controller_Action
{
    public function init()
    {
    }

    public function indexAction()
    {
        $registry = Zend_Registry::get('config');   
    	$this->view->baseUrl = $this->getRequest()->getBaseUrl();
	}

	public function registeruserAction()
	{
		$form = new Default_Form_Registeruser('');
		$this->view->form = $form;
		
		$url = $_SERVER['REQUEST_URI'];
		$params = explode('/', $url);
		$languagesString = Zend_Registry::get('config')->languages;
		$languages = explode('/', $languagesString);
		$retUrl = "/";
		$lang = "";
		if (in_array($params[1], $languages))
		{
			$lang = "/" . $params[1];	
			for ($i = 1; $i < count($params); ++$i){
				if ($params[$i] != ""){
					$retUrl = $retUrl . $params[$i] . "/";
				}
			}
		}
		else
		{
			for ($i = 1; $i < count($params); ++$i){
				if ($params[$i] != ""){
					$retUrl = $retUrl . $params[$i] . "/";
				}
			}
		}
		
		if($this->getRequest()->isPost())
		{
			try {
				$data = $this->_request->getPost();
				if ($form->isValid($data)) {
					$userData = array(
						'Firstname' => $data['firstName'],
						'Lastname' => $data['lastName'],
						'Sex' => $data['sex'],
						'Language' => $data['language'],
						'Username' => $data['username'],
						'Password' => md5($data['password1']),
						'Email' => $data['email1'],
						'Role' => 'member',
						'Active' => false
					);
			    	$user = new Default_Model_User($userData);
					$confirm = new Default_Model_Confirm();
					
					if ($user->emailExists($data['email1']) || $confirm->emailExists($data['email1'])) {
						$this->_helper->getHelper('FlashMessenger')->addMessage(array('message' => Zend_Registry::get('translate')->_('REGISTER_USER_EMAIL_EXISTS_MESSAGE'),'status' => 'warning'));
						$this->_helper->getHelper('Redirector')->gotoUrl('/register');						
					}

					if ($user->usernameExists($data['username'])) {
						$this->_helper->getHelper('FlashMessenger')->addMessage(array('message' => Zend_Registry::get('translate')->_('REGISTER_USER_USERNAME_EXISTS_MESSAGE'),'status' => 'warning'));
						$this->_helper->getHelper('Redirector')->gotoUrl('/register');						
					}

        			$id = $user->save();
					$confirm->insertConfirmationKey($id, md5($data['username'] . $data['email1'] . date('mY')), $data['email1']);
	
					try {
						$mail = new Zend_Mail('UTF-8');
						$confirmationLink = "http://www.spagooy.com/register/".md5($data['username'] . $data['email1'] . date('mY'));
						$confirmationLink = "<a href='" . $confirmationLink . "'>Klicka</a>";
						$body = "<h1>Hej!</h1><br /><div>Välkommen till Spagooy.</div><br />Vänligen aktivera ditt konto genom att klicka på länken:<br />$confirmationLink" ;
						$mail->setBodyHtml($body);
						$mail->setFrom('info@spagooy.com', 'Spagooy');
						$mail->addTo($data['email1'], 'Magnus Spång');
						$mail->setSubject('Registerering hos Spagooy');
						$mail->send();
					} catch (Exception $e) {
						Zend_Registry::get('errLog')->err('Could not send mail to new member.');
						$this->_helper->getHelper('FlashMessenger')->addMessage(array('message' => Zend_Registry::get('translate')->_('REGISTER_USER_ERROR_MESSAGE'),'status' => 'warning'));
						$this->_helper->getHelper('Redirector')->gotoUrl($retUrl);
						// ta bort key och användare
					}
					Zend_Registry::get('userLog')->logusers('New user registred: Id = ' . $id . ', First name = ' . $data['firstName'] . ', Lastname = ' . $data['lastName'] . ', Sex = ' . $data['sex'] . ', Language = ' . $data['language'] . ', Username = ' . $data['username'] . ', Password = ' . $data['password1'] . ', Email = ' . $data['email1']);
					$this->_helper->getHelper('FlashMessenger')->addMessage(array('message' => Zend_Registry::get('translate')->_('REGISTER_USER_OK_MESSAGE'),'status' => 'success'));
					$this->_helper->getHelper('Redirector')->gotoUrl($lang . '/register');
				}
			} catch(Exception $e) {				
				Zend_Registry::get('errLog')->err('Could not register new user: ' . $e);
				$this->_helper->getHelper('FlashMessenger')->addMessage(array('message' => Zend_Registry::get('translate')->_('REGISTER_USER_ERROR_MESSAGE'),'status' => 'error'));
				$this->_helper->getHelper('Redirector')->gotoUrl($retUrl);
			}
		}
	}
	
	public function confirmuserAction()
	{
		try
		{
			$url = $_SERVER['REQUEST_URI'];
			$params = explode('/', $url);
			$key = $params[2];
	    	$confirm = new Default_Model_Confirm();
			$userId = $confirm->confirmNewUser($key);
			if ($userId = $confirm->confirmNewUser($key)) {		
				$user = new Default_Model_User();				
				$data = array(
					'spagooy_user_active' => true
				);
				$user->activateUser($data, $userId);
				$confirm->deleteConfirmationKey($userId);
				$this->view->message = Zend_Registry::get('translate')->_('COFIRMATION_OK');
			} else {	
				$this->view->message = Zend_Registry::get('translate')->_('COFIRMATION_NOT_OK');
			}
		} catch(Exception $e) {
			$this->view->message = Zend_Registry::get('translate')->_('COFIRMATION_ERROR');
		}
	}
	
	public function ajaxregistervalidationAction()
	{
		if(isset($_GET['username']))
		{
			$username = $_GET['username'];
		
			$this->_helper->layout->disableLayout();
			
			if(Default_Model_Validator::validateUsername($username))
			{
				$user = new Default_Model_User();
				if($user->usernameExists($username))
				{
					$this->view->status = "1";
					$this->view->message = Zend_Registry::get('translate')->_('USERNAME_EXISTS');
				}
				else
				{
					$this->view->status = "0";
				}
			}
			else
			{
				$this->view->status = "2";
			}
		}
		
		else if(isset($_GET['email']))
		{
			$email = $_GET['email'];
		
			$this->_helper->layout->disableLayout();
			
			if(Default_Model_Validator::validateEmail($email))
			{
				$user = new Default_Model_User();
				if($user->emailExists($email))
				{
					$this->view->status = "1";
					$this->view->message = Zend_Registry::get('translate')->_('EMAIL_EXISTS');
				}
				else
				{
					$this->view->status = "0";
				}
			}
			else
			{
				$this->view->status = "2";
			}
		}		
	}	
}

